<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="/static/css/home.css">
</head>
<body>
  <h2>这是home</h2>
  <button class="add">点击新增一个学生</button>
  <ul>
    <% for(var i=0;i<stus.length;i++) { %>
    <li>
      <h4>学生姓名: <%= stus[i].stuName %></h4>
      <p>学生年龄: <%= stus[i].stuAge %></p>
      <p>学生性别: <%= stus[i].stuGender == 0?'男':'女' %></p>
      <button class="del" data-id="<%= stus[i]._id  %>">删除学生</button>
      <button class="update" data-id="<%= stus[i]._id  %>">更新</button>
    </li>
    <%}%>
  </ul>
  <script src="/static/js/axios.js"></script>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
  <script>
    $('.add').click(function(){
      axios.post('/addStu', {
        stuName: '学生n',
        stuAge: 20
      }).then(res => {
        if(res.data.code === 200) {
          alert('增加成功');
          // 刷新页面拿到最新数据
          history.go(0);
        }
      })
    })

    // 删除
    $('.del').click(function(){
      // 获取绑定自定义数据 id
      if(confirm('您确认删除吗')){
        axios.delete('/delItem', {
          params: {
            _id: this.dataset.id
          }
        }).then(res => {
          if(res.data.code === 200) {
            alert(res.data.msg);
            history.go(0)
          }
        })
      }
    })

    // 删除
    $('.update').click(function(){
      // 获取绑定自定义数据 id
      axios.put('/updateStu', {
        _id: this.dataset.id,
        stuAge: 100
      }).then(res => {
        if (res.data.code === 200) {
          alert(res.data.msg)
          history.go(0)
        }
      })
    })
  </script>
</body>
</html>